<?php

namespace IDock\Insurance\TAIC\Request;

use IDock\Insurance\TAIC\Response\PremiumInquiryResponse;
use IDock\Insurance\TAIC\TAICEnums;
use IDock\Printer\NonCar\NonCarSubCoveragePrinter;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumChargingPileVisitor;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumDeviceVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;

class PremiumInquiryRequest extends AllTAICRequest
{
    protected $route = 'access/car/premiumAccurate.mvc';

    protected $response = PremiumInquiryResponse::class;

    protected $urlTip = '精确报价';

    //新能源险种
    private $newKindList = [];

    /*** @var  PremiumInquiryVisitor $visitor */
    protected $visitor;

    public function generate(): array
    {
        $this->setTradeNo();

        $data = [
            'quotationType' => '',
            'cityCode' => $this->visitor->getExtInfoVisitor()->argc['cityCode'],
            'startDate' => '',
            'endDate' => '',
            'startDateBus' => '',
            'endDateBus' => '',
            'carInfoDto' => $this->getCarInfo(), //车辆信息
            'combosList' => [$this->getKindItem()], //商业险套餐信息
            'extendInfoList' => [], //扩展信息
            'checkList' => [], //转保校验信息
            'deviceList' => [], //新增设备信息
            'thirdOperatorCode' => '',
            'thirdOperatorName' => '',
            'isLoanCar' => '0',
            'beneficiaryName' => '',
            'paymentMode' => '',
            'expectDiscount' => $this->visitor->getExtInfoVisitor()->expectedDiscount,
            'feeCostFlag' => '',
            'fjSaleRateCom' => '',
            'fjSaleRateCTP' => '',
            'agentMode' => '',
            'intermediaryCode' => '',//$this->visitor->getExtInfoVisitor()->argc['intermediaryCode']
            'companyCode' => $this->visitor->getExtInfoVisitor()->argc['companyCode'] ?? '',
            'teamCode' => $this->visitor->getExtInfoVisitor()->argc['teamCode'] ?? '',
            'taxFlag' => TAICEnums::$taxTypeCode[$this->visitor->getCarTaxVisitor()->taxTypeCode],
            'premiumType' => '1',
            'netServiceCode' => $this->visitor->getExtInfoVisitor()->argc['netServiceCode'] ?? '',
        ];

        if ($this->visitor->getDeviceList()) {
            $data['deviceList'] = $this->getDeviceList();
        }

        if ($this->visitor->ciEffectFlag or $this->visitor->biEffectFlag) {
            if ($this->visitor->ciEffectFlag and $this->visitor->biEffectFlag) {
                $data['paymentMode'] = '1';
            }
            if ($this->visitor->ciEffectFlag and !$this->visitor->biEffectFlag) {
                $data['paymentMode'] = '3';
            }
            if ($this->visitor->biEffectFlag and !$this->visitor->ciEffectFlag) {
                $data['paymentMode'] = '4';
            }

        }

        if ($paidTaxDto = $this->paidTax()) {
            $data['paidTaxDto'] = $paidTaxDto;
        }

        if ($this->visitor->ciStartData and $this->visitor->biStartData) {
            $data['quotationType'] = '3';

            //if ($this->visitor->ciStartData == $this->visitor->biStartData) {
            //    $data['startDate'] = $this->visitor->biStartData;
            //    $data['endDate'] = $this->visitor->biEndData;
            //} else {
            //    $data['startDate'] = $this->visitor->ciStartData;
            //    $data['endDate'] = $this->visitor->ciEndData;
            //    $data['startDateBus'] = $this->visitor->biStartData;
            //    $data['endDateBus'] = $this->visitor->biEndData;
            //}

            $data['startDate'] = $this->visitor->ciStartData;
            $data['endDate'] = $this->visitor->ciEndData;
            $data['startDateBus'] = $this->visitor->biStartData;
            $data['endDateBus'] = $this->visitor->biEndData;

        }
        if ($this->visitor->ciStartData and !$this->visitor->biStartData) {
            $data['startDate'] = $this->visitor->ciStartData;
            $data['endDate'] = $this->visitor->ciEndData;
            $data['quotationType'] = '1';
        }
        if ($this->visitor->biStartData and !$this->visitor->ciStartData) {
            $data['startDate'] = $this->visitor->biStartData;
            $data['endDate'] = $this->visitor->biEndData;
            $data['quotationType'] = '2';
        }

        if ($this->visitor->getVehicleVisitor()->isNewEnergy) {
            $data['premiumType'] = '3';
        }

        //驾意险
        if ($this->visitor->getNonCarInquiryVisitor()->getNonCarList()) {
            $data = $this->getNonCarInfo($data);
        }
        return $data;
    }

    private function getCarInfo(): array
    {
        $data = [
            'licenseNo' => !$this->visitor->getVehicleVisitor()->isNewVehicle ? $this->visitor->getVehicleVisitor()->licenseNo : "",
            'engineNo' => $this->visitor->getVehicleVisitor()->engineNo,
            'frameNo' => $this->visitor->getVehicleVisitor()->vin,
            'brandName' => $this->visitor->getVehicleVisitor()->argc['brandName'] ?? '',
            'printBrandName' => $this->visitor->getVehicleVisitor()->vehicleModel,
            'rbCode' => $this->visitor->getVehicleVisitor()->vehicleModelCode,
            'enrollDate' => $this->visitor->getVehicleVisitor()->firstRegisterDate,
            'ecdemicFlag' => $this->visitor->getVehicleVisitor()->nonlocalCar,
            'transferFlag' => ($this->visitor->getVehicleVisitor()->isTransfer or $this->visitor->getVehicleVisitor()->isCiTransfer) ? '1' : '0',
            'transferDate' => $this->visitor->getVehicleVisitor()->transferDate,
            'seatCount' => $this->visitor->getVehicleVisitor()->vehicleSeat,
            'carOwner' => $this->visitor->getOwnerVisitor()->name,
            'carOwnerIdentifyNumber' => $this->visitor->getOwnerVisitor()->certificateNo,
            'carOwnerIdentifyType' => TAICEnums::$certificateTypeCode[$this->visitor->getOwnerVisitor()->certificateTypeCode] ?? '',
            'carUseType' => TAICEnums::$causeType[$this->visitor->getVehicleVisitor()->causeType],
            'actualValue' => $this->visitor->getVehicleVisitor()->actualValue,
            'purchasePrice' => $this->visitor->getVehicleVisitor()->vehiclePrice,
            'importFlag' => TAICEnums::$importFlag[$this->visitor->getVehicleVisitor()->vehicleImport] ?? '',
            'fuelType' => TAICEnums::$importFlag[$this->visitor->getVehicleVisitor()->energyTypeCode] ?? '',
            'tonCount' => $this->visitor->getVehicleVisitor()->vehicleTonnage,
            'exhaustScale' => $this->visitor->getVehicleVisitor()->vehicleExhaust * 1000,
            'carName' => $this->visitor->getVehicleVisitor()->vehicleName,
            'hyModelCode' => $this->visitor->getVehicleVisitor()->argc['hyModelCode'] ?? '',
            'noticeType' => $this->visitor->getVehicleVisitor()->argc['noticeType'] ?? '',
            'wholeWeight' => $this->visitor->getVehicleVisitor()->wholeWeight,
            'vehicleJingyouDto' => $this->visitor->getVehicleVisitor()->argc['vehicleJY'] ?? '',
            'licenseType' => '',
            'vehicleCategory' => $this->visitor->getVehicleVisitor()->vehicleStyleCode,
            'attachNature' => $this->visitor->getVehicleVisitor()->attachNature,
            'vehicleType' => $this->visitor->getVehicleVisitor()->carKindCode,
            'pureRange' => $this->visitor->getVehicleVisitor()->pureRange,

            'colorCode' => TAICEnums::$vehicleColor[$this->visitor->vehicleVisitor->vehicleColor][0] ?? '',
            'colorName' => TAICEnums::$vehicleColor[$this->visitor->vehicleVisitor->vehicleColor][1] ?? '',
        ];

        //新车备案
        if ($this->visitor->vehicleVisitor->carCertificateType) {
            $data['certificateType'] = $this->visitor->vehicleVisitor->carCertificateType;
            $data['certificateNo'] = $this->visitor->vehicleVisitor->carCertificateNo;
            $data['certificateDate'] = $this->visitor->vehicleVisitor->carCertificateDate;
        }

        //充电桩
        if ($chargingPostInfo = $this->chargingPostInfo()) {
            $data['chargingPostInfoList'] = $chargingPostInfo;
        }

        if ($this->visitor->getOwnerVisitor()->typeCode == 'R1') {
            $data['insuredTypeCode'] = '1';
            $data['useNatureCode'] = '210';
        } elseif ($this->visitor->getOwnerVisitor()->typeCode == 'R3') {
            $data['insuredTypeCode'] = '5';
            $data['useNatureCode'] = '220';
        } else {
            $data['insuredTypeCode'] = '2';
            $data['useNatureCode'] = '230';
        }

        return $data;
    }

    private function getKindItem(): array
    {
        $itemKindList = [];
        foreach ($this->visitor->getCoverageVisitorList() as $visitor) {
            /*** @var $visitor PremiumCoverageVisitor */
            $item = [
                'kindCode' => TAICEnums::$coverageCode[$visitor->coverageCode] ?? '',
                'quantity' => $visitor->quantity,
                'unitAmount' => $visitor->unitAmount,
                'amount' => $visitor->amount,
                'deductableFlag' => '0',
                'deductibleRate' => '0',
                'valueType' => '',
                'chargerNo' => '',
                'shareMIAmountFlag' => '',
            ];
            //共享保额
            if (in_array($item['kindCode'], ['78', '89', '88'])) {
                $item['shareMIAmountFlag'] = (int)$visitor->isShare;
            }

            //去除交强险
            if (!$item['kindCode']) {
                continue;
            }

            $item['kindName'] = TAICEnums::$coverageName[$item['kindCode']];

            //司机险
            if ($item['kindCode'] == '041') {
                $item['quantity'] = 1;
            }
            //乘客险
            if ($item['kindCode'] == '044') {
                $item['quantity'] = $this->visitor->getVehicleVisitor()->vehicleSeat - 1;
            }
            //服务次数
            if (in_array($item['kindCode'], ['79', '80', '81', '82'])) {
                $item['quantity'] = $visitor->serviceTimes;
            }

            //医保外乘客用药
            if ($visitor->coverageCode == 'C05003' or $visitor->coverageCode== 'C15003') {
                $item['quantity'] = $this->visitor->getVehicleVisitor()->vehicleSeat - 1;
                $item['unitAmount'] = $item['amount'];
                $item['amount'] = $item['unitAmount'] * $item['quantity'];
            }

            if ($item['kindCode'] == '607' or $item['kindCode'] == '609') {
                continue;
            }

            $itemKindList[] = $item;
        }

        $itemKindList = array_merge($itemKindList, $this->newKindList);

        return [
            'comboNo' => '1',
            'itemKindList' => $itemKindList
        ];
    }

    private function chargingPostInfo(): array
    {
        $list = [];

        if (!$this->visitor->getChargingPileVisitorList()) {
            return [];
        }

        foreach ($this->visitor->getChargingPileVisitorList() as $visitor) {
            if (!$visitor->chargingPileKind) {
                continue;
            }

            /*** @var  $visitor PremiumChargingPileVisitor */
            $list[] = [
                'chargingPostType' => $visitor->chargingPileType,
                'chargingPostCode' => $visitor->chargingPileCode,
                'chargingPostAddress' => $visitor->chargingPileAddress,
                'chargingPostKind' => TAICEnums::$chargingPileKind[$visitor->chargingPileKind] ?? '',
                'chargingPostAddressEl' => TAICEnums::$chargingPileAddressType[$visitor->chargingPileAddressType] ?? '',
                'chargingPostUseAge' => TAICEnums::$chargingPileYearLimit[$visitor->chargingPileYearLimit] ?? '',
                'chargerNo' => $visitor->seqNo
            ];

            //新能源险种--损失
            if ($visitor->lossAmount) {
                $this->newKindList[] = [
                    'kindCode' => '607',
                    'kindName' => '附加自用充电桩损失保险',
                    'quantity' => '',
                    'unitAmount' => '',
                    'amount' => $visitor->lossAmount,
                    'deductableFlag' => '0',
                    'deductibleRate' => '0',
                    'valueType' => '',
                    'chargerNo' => $visitor->seqNo,
                    'shareMIAmountFlag' => '',
                ];
            }
            //新能源--责任
            if ($visitor->liabilityAmount) {
                $this->newKindList[] = [
                    'kindCode' => '609',
                    'kindName' => '附加自用充电桩责任保险',
                    'quantity' => '',
                    'unitAmount' => '',
                    'amount' => $visitor->liabilityAmount,
                    'deductableFlag' => '0',
                    'deductibleRate' => '0',
                    'valueType' => '',
                    'chargerNo' => $visitor->seqNo,
                    'shareMIAmountFlag' => '',
                ];
            }
        }

        return $list;
    }

    private function paidTax(): array
    {
        if (!$this->visitor->getCarTaxVisitor()->taxDocumentNumber) {
            return [];
        }
        return [
            'taxDeptCode' => $this->visitor->getCarTaxVisitor()->taxDepartmentCode,
            'taxDeptName' => $this->visitor->getCarTaxVisitor()->taxDepartment,
            'paidFreeCertificate' => $this->visitor->getCarTaxVisitor()->taxDocumentNumber,
            'paidDocumentDate' => $this->visitor->getCarTaxVisitor()->taxDocumentDate,
            'paidAreaCode' => $this->visitor->getCarTaxVisitor()->taxPaidAreaCode,
        ];
    }

    private function getNonCarInfo($data): array
    {
        /*** @var $single NonCarProductVisitor */
        $single = $this->visitor->getNonCarInquiryVisitor()->getNonCarList()[0] ?? [];

        //组合险种
        if ($single->productCode == '0000')  {
            /*** @var $subCoverage NonCarSubCoveragePrinter */
            foreach ($single->subCoverage as $subCoverage) {
                $data['combineProductList'][] = [
                    "productCode" => $subCoverage->argc['productCode'] ?? '',
                    "unitAmount" => $subCoverage->amount,
                    "planCode" => $subCoverage->subCode,
                    "unitPremium" => $subCoverage->premium,
                    "numberOfCopies" => '1',
                    'duePremium' => $subCoverage->premium,
                    'combinPlanCode' => $single->productCode .'-'.$single->planCode
                ];
            }
        } else {
            $data['combineProductList'][] = [
                "productCode" => $single->productCode,
                "unitAmount" => floatval($single->argc['amount'] ?? '0'),
                "planCode" => $single->planCode,
                "unitPremium" => $single->premium,
                "numberOfCopies" => $single->insuredNum,
                "duePremium" => round($single->premium * $single->insuredNum, 2),
            ];
        }

        return $data;
    }

    /**
     * 新增设备
     * @return array
     */
    private function getDeviceList(): array
    {
        $deviceList = [];
        /*** @var PremiumDeviceVisitor $device */
        foreach ($this->visitor->getDeviceList() as $key => $device) {
            $deviceList[] = [
                'serialNo' => $key + 1,
                'deviceName' => $device->deviceName,
                'deviceCount' => $device->quantity,
                'purchasePrice' => $device->purchasePrice,
                'newBuyDate' => $device->buyDate
            ];
        }
        return $deviceList;
    }
}
